from django.contrib.auth import login
from django.http import JsonResponse, HttpResponse, HttpResponseForbidden
from django.shortcuts import render, redirect

# Create your views here.
from django.views import View
from  AgentLogin import AgentLogin
from django.conf import Settings
from .models import QQAuthUser
from .utils import generate_secret_openid


class QQLoginView(View):
    def get(self,request):
        '''
           get  the qq scan-login link address
            获取qq扫码登陆链接地址

        :param request:
        :return:
        '''
        qq_url=AgentLogin.qq_url()   #需要传递三个参数
        return JsonResponse({'code':200,'errormsg':'OK','login_url':qq_url})

class QQAuthUserView(View):
    def get(self,request):
        '''

        获取openid
        :param request:
        :return:
        '''
        code=request.GET.get('code','')
        if not code :
            return  HttpResponseForbidden('缺少必传参数')

        nickname,openid=AgentLogin.qq()  #传递参数
        try:

            qq_user=QQAuthUser.objects.get(openid=openid)
        except:

            #如果没有绑定用户

            #加密openid
            sec_openid=generate_secret_openid(openid)
            #传递加密数据给用户绑定页面
            return  render(request,'oauth/oauth_user.html', {'sec_openid':sec_openid})


        else:
            #已绑定用户
            #实现状态保持
            mg_user=qq_user.user
            login(request,mg_user)
            return redirect(reverse('newsapp:index'))



        return  HttpResponse('hello qq')


